<?php

namespace Frontend\Controllers;

use Forms\LoginForm;
use Forms\SignUpForm;
use Forms\ResetForm;
use Forms\EdituserForm;
use Forms\ChangepassForm;
use Models\Users;
use Models\EmailConfirmations;
use Forms\PhoneCartForm;
use Library\Gamebank;
use Models\Transactions;

class UserController extends ControllerBase {

    public function indexAction() {
        
    }

    public function signupAction() {
        $form = new SignUpForm();
        if ($this->request->isPost()) {
            if ($form->isValid($this->request->getPost())) {
                $user = new Users();

                $point = 0;
                $balance = 0;
                $balance_obj = \Models\References::findFirstById('balance');
                if ($balance_obj) {
                    $balance = $balance_obj->value;
                }
                $point_obj = \Models\References::findFirstById('point');
                if ($point_obj) {
                    $point = $point_obj->value;
                }

                $user->assign(array(
                    'username' => $this->request->getPost('username', 'striptags'),
                    'email' => $this->request->getPost('email'),
                    'password' => $this->security->hash($this->request->getPost('password')),
                    'fullName' => $this->request->getPost('name'),
                    'role_id' => 1,
                    'points' => $point,
                    'balance' => $balance,
                    'expired' => date('Y-m-d')
                ));
                if ($user->save()) {
                    return $this->response->redirect('login');
                } else {
                    foreach ($user->getMessages() as $value) {
                        $form->appendMessage($value, "signupsuccess", null);
                    }
                }
            }
        }
        $this->view->form = $form;
    }

    public function loginAction() {
        $identity = $this->auth->getIdentity();
        if ($identity) {
            return $this->response->redirect('profile');
        }
        $form = new LoginForm();
        if (!$this->request->isPost()) {

            if ($this->auth->hasRememberMe()) {
                $this->auth->loginWithRememberMe();
                return false;
            }
        } else {

            //valdate and print error in LoginForm function messages
            if ($form->isValid($this->request->getPost()) == true) {
                try {
                    $this->auth->check(array(
                        'username' => $this->request->getPost('username'),
                        'password' => $this->request->getPost('password'),
                        'remember' => $this->request->getPost('remember'),
                    ));

                    if ($this->request->getQuery('url') == true) {
                        //var_dump($this->request->getQuery('url'));
                        header('Location:' . $this->request->getQuery('url'));
                        return false;
                    }
                    header("Refresh:0");
                    /*                     * header('Location: index');
                      return false;* */
                } catch (\Library\Exception $e) {
                    $form->appendMessage($e->getMessage(), "loginfail", null);
                }
            }
        }
        $this->view->form = $form;
    }

    /**
     * Confirms an e-mail, if the user must change its password then changes it
     */
    public function confirmEmailAction() {
        $code = $this->dispatcher->getParam('code');

        $confirmation = EmailConfirmations::findFirstByCode($code);
        if (!$confirmation) {
            return $this->response->redirect('user/errorConfirm');
        }
        if ($confirmation->confirmed <> 'N') {
            $this->flash->success('The email was successfully confirmed. Now, please change your password for security!');
            return $this->response->redirect('login');
        }
        //confirmation
        $confirmation->confirmed = 'Y';
        $confirmation->user->active = 'Y';
        /**
         * Change the confirmation to 'confirmed' and update the user to 'active'
         */
        if ($confirmation->save()) {
            return $this->response->redirect('login');
        } else {
            foreach ($confirmation->getMessages() as $message) {
                $this->flash->error($message);
            }
        }
    }

    public function resetpasswordAction() {
        $form = new ResetForm();
        if ($this->request->isPost()) {
            if ($form->isValid($this->request->getPost())) {
                $user = Users::findFirstByEmail($this->request->getPost('email'));
                if ($user) {
                    $newpss = $this->RandomString(10);
                    $user->password = $this->security->hash($newpss);
                    if ($user->save()) {
                        $mail_params = array(
                            'password' => $newpss,
                            'user' => $user,
                        );
                        $this->getDI()->getMail()->send($user->email, "Reset Password Email", 'resetpass', $mail_params);
                        $form->appendMessage("Vui lòng kiểm tra email để đăng nhập tài khoản", "form", null);
                    }
                } else {
                    $form->appendMessage("Email không được tìm thấy trong dữ liệu", "form", null);
                }
            }
        }
        $this->view->form = $form;
    }

    public function logoutAction() {
        $this->auth->remove();
        return $this->response->redirect();
    }

    public function profileAction() {
        $form = new EdituserForm();
        $identity = $this->auth->getIdentity();
        $user = Users::findFirstById($identity['id']);
        if ($user) {
            $this->view->userfullname = $user->fullName;
            $form = new EdituserForm($user);
            if ($this->request->isPost()) {
                $request = $this->request->getPost();
                //$request['username'] = $user->username;
                //$request['email'] = $user->email;
                if ($form->isValid($request)) {
                    $user->address = $this->request->getPost('address');
                    $user->fullName = $this->request->getPost('fullName');
                    $user->updatetime = date('Y-m-d H:i:s');
                    if ($user->save()) {
                        $form->appendMessage("Cập nhật thành công", "editprofile_info", null);
                    } else {
                        $form->appendMessage("fail", "editprofile_info", null);
                    }
                    foreach ($user->getMessages() as $value) {
                        $form->appendMessage($value, "editprofile_info", null);
                    }
                }
            }
            $this->view->form = $form;
            $this->view->users = $user;
        } else {
            $this->dispatcher->forward(array(
                'module' => 'admin',
                'controller' => 'error',
                'action' => 'notAvailable'
            ));
        }
    }

    public function changepassAction() {
        $form = new ChangepassForm();
        $identity = $this->auth->getIdentity();
        $user = Users::findFirstById($identity['id']);
        if ($user) {
            $this->view->userfullname = $user->fullName;
            $password = $user->password;
            $user->password = '';
            $form = new ChangepassForm($user);
            if ($this->request->isPost()) {
                $request = $this->request->getPost();
                //$request['username'] = $user->username;
                //$request['email'] = $user->email;
                if ($form->isValid($request)) {
                    if ($this->request->getPost('password')) {
                        $user->password = $this->security->hash($this->request->getPost('password'));
                    } else {
                        $user->password = $password;
                    }
                    $user->updatetime = date('Y-m-d H:i:s');
                    if ($user->save()) {
                        $form->appendMessage("Thay đổi mật khẩu thành công", "changepass_info", null);
                    } else {
                        $form->appendMessage("Cập nhật lỗi", "changepass_info", null);
                    }
                    foreach ($user->getMessages() as $value) {
                        $form->appendMessage($value, "changepass_info", null);
                    }
                }
            }
            $this->view->form = $form;
            $this->view->users = $user;
        } else {
            $this->dispatcher->forward(array(
                'module' => 'admin',
                'controller' => 'error',
                'action' => 'notAvailable'
            ));
        }
    }

    public function downhistoryAction() {
        $identity = $this->auth->getIdentity();
        $user = Users::findFirstById($identity['id']);
        if ($user) {
            $this->view->userfullname = $user->fullName;
            $query = $this->modelsManager->createBuilder()
                    ->columns(array(
                        'Models\Downloads.id',
                        'Models\Downloads.doc_id',
                        'Models\Documents.title',
                        'Models\Documents.image',
                        'Models\Documents.download',
                        'Models\Documents.topic_id',
                        'Topics.name TopicName',
                        'Models\Downloads.time',
                    ))
                    ->from('Models\Downloads')
                    ->join('Models\Documents', 'Models\Documents.id = Models\Downloads.doc_id')
                    ->leftjoin('Models\Topics', 'Topics.id = Models\Documents.topic_id', 'Topics')
                    ->where('Models\Downloads.user_id = \'' . $identity['id'] . '\'');
            $docs = $query->getQuery()->execute();
            $currentPage = (int) $this->request->getPost('page');
            if (!$currentPage) {
                $currentPage = 1;
            }
            $limit = (int) $this->request->getPost('limit');
            if (!$limit) {
                $limit = 10;
            }
            $pagintion = new \Phalcon\Paginator\Adapter\Model(
                    array(
                "data" => $docs,
                "limit" => $limit,
                "page" => $currentPage
                    )
            );
            $this->view->docs = $pagintion->getPaginate();
            $this->view->users = $user;
            $this->view->page = $currentPage;
            $this->view->limit = $limit;
        } else {
            $this->dispatcher->forward(array(
                'module' => 'frontend',
                'controller' => 'user',
                'action' => 'login',
            ));
        }
    }

    public function uploadhistoryAction() {
        $identify = $this->auth->getIdentity();
        $user = Users::findFirstById($identify['id']);
        if ($user) {
            $this->view->userfullname = $user->fullName;
            $query = $this->modelsManager->createBuilder()
                    ->columns(array(
                        'Models\Documents.id',
                        'Models\Documents.title',
                        'Models\Documents.image',
                        'Models\Documents.download',
                        'Models\Documents.topic_id',
                        'Topics.name TopicName',
                        'Models\Documents.submit_date',
                    ))
                    ->from('Models\Documents')
                    ->leftjoin('Models\Topics', 'Topics.id = Models\Documents.topic_id', 'Topics')
                    ->where('Models\Documents.uploadby = \'' . $identify['id'] . '\'');
            $docs = $query->getQuery()->execute();
            $currentPage = (int) $this->request->getPost('page');
            if (!$currentPage) {
                $currentPage = 1;
            }
            $limit = (int) $this->request->getPost('limit');
            if (!$limit) {
                $limit = 10;
            }
            $pagintion = new \Phalcon\Paginator\Adapter\Model(
                    array(
                "data" => $docs,
                "limit" => $limit,
                "page" => $currentPage
                    )
            );
            $this->view->docs = $pagintion->getPaginate();
            $this->view->users = $user;
            $this->view->page = $currentPage;
            $this->view->limit = $limit;
        } else {
            $this->dispatcher->forward(array(
                'module' => 'frontend',
                'controller' => 'user',
                'action' => 'login',
            ));
        }
    }

    public function rechargeAction() {
        $identity = $this->auth->getIdentity();
        $user = Users::findFirstById($identity['id']);
        if (!$user) {
            return $this->response->redirect('login?url=/vids/recharge');
        }
        $this->view->userfullname = $user->fullName;
        $this->view->balance = $user->balance;
        $this->view->expired = $user->expired;
            $this->view->point = $user->points;
        $form = new PhoneCartForm();
        if ($this->request->getPost()) {
            if ($form->isValid($this->request->getPost())) {
                $challenge = $this->request->getPost('recaptcha_challenge_field');
                $respone = $this->request->getPost('recaptcha_response_field');
                $answer = $this->captcha->check('6LcE-PcSAAAAABuNKgjv0LpKUUGDlQ7Ob66-mR8i', 'localhost', $challenge, $respone);
                if ($answer) {
                    $telco = $this->request->getPost('rthecao');
                    $code = $this->request->getPost('pin');
                    $seri = $this->request->getPost('serial');
                    $gb = new Gamebank();
                    $balance_change = 0;
                    $result = $gb->checkout($telco, $code, $seri);
                    if ($result['response'] == 'fail') {
                        $form->appendMessage($result['message'], 'form');
                    } else {
                        if ($result['response'] == 'success') {
                            if ((int) $result['value'] > 10000) {
                                $user->balance += (int) $result['value'] * 1.5;
                                $balance_change = (int) $result['value'] * 1.5;
                            } else {
                                $user->balance += (int) $result['value'];
                                 $balance_change = (int) $result['value'];
                            }
                            $user->updatetime = date('Y-m-d h:i:s');
                            $user->expired = $this->getExpireDate($result['value'], $user->expired, 1);
                            $user->save();
                            $transaction = new Transactions();
                            $transaction->assign(array(
                                'user_id' => $user->id,
                                'money' => (int) $result['value'],
                                'balance_change' => $balance_change,
                                'type' => 'Thẻ cào điện thoại',
                                'date' => date('Y-m-d h:i:s'),
                                'transaction_code' => $result['code'],
                            ));
                            $transaction->save();
                            $form->appendMessage($result['message'], 'form');
                        }
                    }
                } else {
                    $form->appendMessage('Mã bảo mật không đúng', 'captcha');
                }
            }
        }
        $this->view->form = $form;
    }

    public function exchangeAction() {
        $identity = $this->auth->getIdentity();
        $user = Users::findFirstById($identity['id']);
        if ($user) {
            $this->view->userfullname = $user->fullName;
            $transactions = Transactions::find('user_id=\'' . $user->id . '\'');
            $total = 0;
            foreach ($transactions as $transaction) {
                $total += (int) $transaction->balance_change;
            }
            $currentPage = (int) $this->request->getPost('page');
            if (!$currentPage) {
                $currentPage = 1;
            }
            $limit = (int) $this->request->getPost('limit');
            if (!$limit) {
                $limit = 10;
            }
            $pagintion = new \Phalcon\Paginator\Adapter\Model(
                    array(
                "data" => $transactions,
                "limit" => $limit,
                "page" => $currentPage
                    )
            );
            $this->view->transactions = $pagintion->getPaginate();
            $this->view->page = $currentPage;
            $this->view->limit = $limit;
            $this->view->total = $total;
        } else {
            return $this->dispatcher->forward(array(
                        'module' => 'frontend',
                        'controller' => 'user',
                        'action' => 'login',
            ));
        }
    }

    public function rechargebypointAction() {
        $this->view->disable();
        $identity = $this->auth->getIdentity();
        $user = Users::findFirstById($identity['id']);
        if (!$user) {
            echo 'Bạn chưa đăng nhập! Vui lòng đăng nhập tại <a href="' . $this->url->get('login') . '">đây</a>';
            return;
        }
        $value = (int)$this->request->getPost('point');
        if ($value > $user->points) {
            echo 'Số điểm của bạn hiện không đủ để thực hiện giao dịch này!';
            return;
        }
        $expired = $this->getExpireDate($value, $user->expired, 2);
        $balance_change = 0;
        if (!$expired) {
            echo 'Giá trị bạn chọn không nằm trong danh mục cho phép';
            return;
        }
        switch ($value) {
            case '100':
                $user->points -= 100;
                $user->balance += 1000;
                $balance_change = 1000;
                $user->expired = $expired;
                break;
            case '200':
                $user->points -= 200;
                $user->balance += 3000;
                $balance_change = 3000;
                $user->expired = $expired;
                break;
            case '300':
                $user->points -= 300;
                $user->balance += 5000;
                $balance_change = 5000;
                $user->expired = $expired;
                break;
            default:
                break;
        }
        if ($user->save()) {
             $transaction = new Transactions();
                            $transaction->assign(array(
                                'user_id' => $user->id,
                                'money' => $value,
                                'balance_change' => $balance_change,
                                'type' => 'Đổi ePoints',
                                'date' => date('Y-m-d h:i:s'),
                                'transaction_code' => strtotime(date('Y-m-d h:i:s')),
                            ));
                            $transaction->save();
            echo 'Đổi điểm thành công!';
            return;
        }
    }

    function RandomString($count) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randstring = '';
        for ($i = 0; $i < $count; $i++) {
            $randstring .= $characters[rand(0, strlen($characters))];
        }
        return $randstring;
    }

    function getExpireDate($value, $date, $type) {
        $currentdate = date('Y-m-d');
        if ($currentdate < date($date)) {
            $responsedate = new \DateTime($date);
        } else {
            $responsedate = new \DateTime($currentdate);
        }
        if ($type == 1) {
            switch ($value) {
                case 10000:
                    $responsedate->modify('+15 days');
                    return $responsedate->format('Y-m-d');
                case 20000:
                    $responsedate->modify('+30 days');
                    return $responsedate->format('Y-m-d');
                case 50000:
                    $responsedate->modify('+3 months');
                    return $responsedate->format('Y-m-d');
                case 100000:
                    $responsedate->modify('+6 months');
                    return $responsedate->format('Y-m-d');
                default :
                    if ($value > 100000) {
                        $responsedate->modify('+6 months');
                        return $responsedate->format('Y-m-d');
                    } else {
                        return $date;
                    }
            }
        }
        if ($type == 2) {
            switch ($value) {
                case 100:
                    $responsedate->modify('+5 days');
                    return $responsedate->format('Y-m-d');
                case 200:
                    $responsedate->modify('+15 days');
                    return $responsedate->format('Y-m-d');
                case 300:
                    $responsedate->modify('+1 months');
                    return $responsedate->format('Y-m-d');
                default :
                    return false;
            }
        }
        return $date;
    }

}
